package com.bjpowernode.seckillservice.listener;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bjpowernode.constant.Constants;
import com.bjpowernode.entity.Orders;
import com.bjpowernode.seckillservice.service.OrderService;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

@Component
public class DelayListener {
    @Resource
    private OrderService orderService;

    @RabbitListener(queues = Constants.QUEUE_DELAY_NAME)
    public void onMessage(Message message, Channel channel) {
        String orderId = new String(message.getBody());
        Orders orders = orderService.getById(orderId);
        if (orders.getStatus() == 0) {
            UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("status", 2);
            updateWrapper.set("update_time", new Date());
            updateWrapper.eq("id", orderId);
            boolean updateResult = orderService.update(updateWrapper);
            if (updateResult) {
                try {
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
